const WxParse = require('../../util/wxParse/wxParse')
const app = getApp()
const {getData, request} = require('../../util/request.js')
let time = 0
Page({
    /**
     * 页面的初始数据
     */
    data: {
        videoContext: null,
        videoTime: 0,
        unitId: null,
        title: '',
        is_unlock: 0,
        desc: '',
        html: null,
        tab: 1,
        platform: '',
        videoSrc: '',
        last_page: 1,
        originPrice: 99,
        unionid: null,
        userId: app.globalData.userId,
        course_id: null,
        shareNum: 0,
        requireShare: 2,
        hiddenLayer: true,
        list: [],
        page: 1,
    },
    setTabs(e) {
        this.setData({
            tab: e.currentTarget.dataset.no
        })
    },
    noHandel() {

    },
    closeLayer() {
        this.setData({
            hiddenLayer: true
        })
    },
    showLayer() {
        wx.navigateTo({
            url: `../addWx/addWx?group=0`,
        })
    },
    joinGroup() {
        wx.navigateTo({
            url: `../addWx/addWx?group=1`,
        })
    },
    updateUserInfo(e) {
        console.log(e)
        let link = e.currentTarget.dataset.link
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            app.globalData.userInfo = res.userInfo
                            this.setData({
                                avatarUrl: res.userInfo.avatarUrl,
                                userInfo: res.userInfo
                            })
                            this.onGetOpenid(link)
                        }
                    })
                }
            }
        })
    },
    toRegister() {
        // 已登录 未注册
        wx.showModal({
            title: '未注册',
            content: '前往注册后操作',
            cancelText: '不去',
            confirmText: '去注册',
            cancelColor: '#9a9a9a',
            success(res) {
                if (res.confirm) {
                    wx.navigateTo({
                        url: `../bind/bind`,
                    })
                } else if (res.cancel) {

                }
            }
        })
    },
    onGetOpenid: function (link) {
        // 调用云函数
        let that = this
        wx.cloud.callFunction({
            name: 'login',
            data: {},
            success: (res) => {
                app.globalData.openid = res.result.openid
                app.globalData.unionid = res.result.unionid
                that.setData({
                    openid: res.result.openid,
                    unionid: res.result.unionid
                })
                // 设置本地缓存
                wx.setStorage({
                    key: 'openid',
                    data: res.result.openid,
                })
                wx.setStorage({
                    key: 'unionid',
                    data: res.result.unionid,
                })
                wx.setStorage({
                    key: 'userInfo',
                    data: that.data.userInfo,
                })
                // 登录
                request('/mike/auth/login', "POST", {
                    unionid: res.result.unionid,
                    openid: res.result.openid
                }, function (res) {
                    if (res.error === 0) {
                        if (res.data.auth) {
                            app.globalData.userId = res.data.user.user_id
                            app.globalData.user = res.data.user
                            that.setData({
                                userId: res.data.user.user_id,
                                is_mobile_binded: res.data.user.is_mobile_binded
                            })
                            wx.setStorage({
                                key: 'is_mobile_binded',
                                data: res.data.user.is_mobile_binded
                            })
                            wx.setStorage({
                                key: 'user',
                                data: res.data.user
                            })
                            wx.setStorage({
                                key: 'token',
                                data: res.data.auth.token_type + ' ' + res.data.auth.access_token,
                            })
                            wx.setStorage({
                                key: 'user_id',
                                data: res.data.user.user_id,
                            })
                        } else {
                            // 提示绑定
                            wx.navigateTo({
                                url: `../bind/bind`,
                            })
                        }
                        // wx.navigateTo({
                        //     url: link,
                        // })
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: 'none'
                        })
                    }
                }, function (err) {

                })
            },
            fail: err => {
                // wx.navigateTo({
                //     url: '../deployFunctions/deployFunctions',
                // })
            }
        })
    },
    previewImg(e) {
        wx.getImageInfo({
            src: '../../images/qrcode.jpg',
            success: function (res) {
                var path = res.path;
                wx.saveImageToPhotosAlbum({
                    filePath: path,
                    success: function (res) {
                        // console.log('图片已保存');
                        wx.showToast({
                            title: '图片已保存',
                            icon: 'success',
                            duration: 2000
                        })
                        this.setData({
                            hiddenLayer: true
                        })
                    },
                    fail: function (res) {
                        // console.log('保存失败');
                        wx.showToast({
                            title: '保存失败，请重试',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            }
        });
    },
    playVideo(e) {
        let video = e.currentTarget.dataset.video;
        if (this.data.unitId == video.unit_id) {
            return false
        }

        if (this.data.is_unlock == 0) {
            // 未解锁
            if (video.is_free == 0) {
                wx.showToast({
                    title: '请先分享解锁',
                    icon: 'none',
                    duration: 2000
                })
            } else {
                this.getClassDetail(video.unit_id)
            }

        } else {
            // 已解锁
            this.getClassDetail(video.unit_id)
        }
    },
    timeFormat(second) {
        // 小时位
        let hr = Math.floor(second / 3600);
        let hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = "0" + hrStr;

        // 分钟位
        let min = Math.floor((second - hr * 3600) / 60);
        let minStr = min.toString();
        if (minStr.length == 1) minStr = "0" + minStr;

        // 秒位
        let sec = second - hr * 3600 - min * 60;
        let secStr = sec.toString();
        if (secStr.length == 1) secStr = "0" + secStr;
        let timeStr = ''
        if (hrStr > 0) {
            timeStr = hrStr + ':' + minStr + ':' + secStr
        } else {
            timeStr = minStr + ':' + secStr
        }
        return timeStr;
    },
    // 获取课程列表
    getList() {
        getData(`/mike/course/unit/${this.data.course_id}?page=${this.data.page}`,
            (res) => {
                if (res.error === 0) {
                    let list = this.data.list
                    list = list.concat(res.data.data)
                    this.setData({
                        list: list,
                        last_page: res.data.last_page
                    })
                    if (this.data.page == 1) {
                        this.getClassDetail(list[0].unit_id)
                    }
                }
            },
            (error) => {

            }
        )
    },
    getClassDetail(unitid) {
        this.setData({
            unitId: unitid
        })
        getData(`/mike/unit/${unitid}`,
            (res) => {
                if (res.error == 0) {
                    this.setData({
                        title: res.data.title,
                        desc: res.data.slogan,
                    })
                    let header = {
                        "content-type": "application/json;charset=UTF-8",
                        'Accept': 'application/json',
                    }
                    let token = wx.getStorageSync("token")
                    if (token) {
                        header.Authorization = 'Bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImUwM2I2MjNiNTQ2ZWM1ZmU3NjVmZGU4MWE4YWQ0YTFhZjQzZjNiMWQ1Y2I5Y2FhMjY2NDkxNmJmNDljNWRjNjhiZTBmNTRjNmNlZmYyZmNjIn0.eyJhdWQiOiIxIiwianRpIjoiZTAzYjYyM2I1NDZlYzVmZTc2NWZkZTgxYThhZDRhMWFmNDNmM2IxZDVjYjljYWEyNjY0OTE2YmY0OWM1ZGM2OGJlMGY1NGM2Y2VmZjJmY2MiLCJpYXQiOjE1NDY1NjkwOTIsIm5iZiI6MTU0NjU2OTA5MiwiZXhwIjoxNTQ3ODY1MDkyLCJzdWIiOiI0MzEiLCJzY29wZXMiOltdfQ.JjfZocEblnGiZ2hIO03OytaE9h7OzxKeu5mChXJ2WV9cBnN_qC-fXQnbMAIngq4u7mmhAyAoKGFaWF0D3VXeeVAzFJnR7YpCErexyrMsSkV5Kmuw7JkITn6wMpxk4xVgydrqQvwwyjD5cJsQ0Sv3rmgo2i6-lK_4Os7FPgJ_R0bSLf7oZVnmf2uLvxE3L87M4SLsFzOdOBulnASiSKWumFipSy-MC3I_NahnNGMGQ6xzsyj2G4pGoFcyoNcgCofUuor9Zp5xusI6i8jWj39uvMXXMGwQ6HNp90RC9nqL39xwI01pio1rPxTguR7HInrKnEMjclotvOHAQgXM5rnPZIey8UHzp83J_TLDuZX5VwsdrGm9OtThaleaKrVUZug-yCWYPZeQLMDCtgFln6evE4SyzYXw-JuwHo8fRYacI-NI-d4cqppUKkxTPH_R6dmlcpGzPWmIMpGuJcuy-svMpLpYuLWXFrMXuzg2CWuYS0WUu3BsXMa2Awbi4fYp3xx8Jr2Y2IVIDYYurgEHEAW56is8qNedVu6gh3oD8w0MUjV39M1EuT0kbhvt4sXjgucS7lbJVZq6MKmMc1JyV3tOeKkrv64eGIxPakPDPDewe1UPLD7N52e1lfNGzfGvGvOVtPHReQuR_WuejTCLcMq8_doq8A9HJHMOuJOYE3Un81g'
                    } else {
                        wx.showToast({
                            title: '请先登录',
                            icon: 'none'
                        })
                        return false
                    }
                    var self = this
                    wx.showLoading({
                        mask: true
                    })
                    wx.request({
                        //项目的真正接口，通过字符串拼接方式实现
                        url: `https://bukeapi.gaodunwangxiao.com/gaodun/auth/video?video_id=${res.data.media_url}`,
                        header: header,
                        method: 'GET',
                        success: function (v) {
                            //参数值为res.data,直接将返回的数据传入
                            let url = `http://live-hz.gaodun.com/${v.data.data.user_id}/${v.data.data.token}/${v.data.data.video_id}/HD/1.m3u8`
                            self.setData({
                                videoSrc: url
                            })
                            console.log(url);
                            wx.hideLoading()
                        },
                        fail: function () {
                            wx.showToast({
                                icon: 'none',
                                title: '网络错误，请重试',
                            })
                            wx.hideLoading()
                        },
                    })
                }
            },
            (error) => {

            }
        )
    },
    getClassInfo(id) {
        let that = this;
        getData(`/mike/course/${id}`,
            (res) => {
                if (res.error == 0) {
                    this.setData({
                        title: res.data.title,
                        is_unlock: res.data.is_unlock,
                        desc: res.data.summary,
                        shareNum: res.data.invited_count,
                        originPrice: parseInt(res.data.price)
                    })
                    WxParse.wxParse('html', 'html', res.data.intro, that, 5)
                }
            },
            (error) => {

            }
        )
    },
    // 视频进度更新
    timeUpdate(e) {
        time = e.detail.currentTime
    },
    videoEnded() {
        this.report()
    },
    report() {
        request('/mike/report', 'POST',
            {seek_to: time, unit_id: this.data.unitId},
            (res) => {
            },
            (err) => {
            })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData(({
            course_id: options.course_id
        }))
        this.getList()
        this.getClassInfo(options.course_id)


        // wx.setNavigationBarTitle({
        //     title: '直播'
        // })
        let that = this
        wx.getSystemInfo({
            success(res) {
                that.setData({
                    platform: res.platform
                })
            }
        })
    },
    onReachBottom() {
        if (this.data.tab == 2 && this.data.page < this.data.last_page) {
            let page = this.data.page
            page += 1
            this.setData({
                page: page
            }, () => {
                this.getList()
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.setData({
            unionid: app.globalData.unionid,
            userId: app.globalData.userId
        })
        let videoContext = wx.createVideoContext('myVideo')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.report()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.report()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        return {
            title: '每天半小时，轻松拿本科',
            path: '/pages/index/index',//实验发现，此处的路径应该写全，写到具体的wxml页面。如path:'/page/user/user?id=123'
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },
})
